/**
 * 学生和教师通用接口  修改状态（可用，停用）
 * 
 * /admin/set/status
 */

const User_info = require('../../../models/usersInfo')
const Users = require('../../../models/users')
const utils = require('../../../utils/index')
const MySQLManager = require('../../../utils/MySQLManager');
const $ = require('../../../utils/common')
const sequelize = MySQLManager
const Sequelize = require('sequelize')
const Op = Sequelize.Op

const set_student_status = async function (req, res) {
    try {
        // 传数组
        if (!req.body.id) {
            $.sendMessage(res, 1015, '参数id没有传')
            return
        }

        var ids = req.body.id.split(',')

        //根据id找到响应的user_name ， 用user_name设置
        var user_name_array = await User_info.findAll({
            where: {
                id: {
                    [Op.or]: ids
                }
            },
            attributes: ['user_name']
        })

        // 格式化user_name
        var new_array = user_name_array.map(item => {
            return item.dataValues.user_name + ''
        })
        
        // var user_names = req.body.user_names.split(',')
        // 事务
        return sequelize.transaction(function (t) {
            return Users.update(
            {
                user_status: req.body.user_status
            },
            {
                where: {
                    user_name: {
                        [Op.or]: new_array
                    }
                }
            }
            , 
            {transaction: t}).then(function (user) {
            return User_info.update(
                {
                    user_status: req.body.user_status
                },
                {
                    where: {
                        user_name: {
                            [Op.or]: new_array
                        }
                    }
                }
                , {transaction: t});
            })
        
        }).then(function (result) {
            res.json({
                code: 200,
                message: '修改状态成功',
                result: result
            })
            // 事务已被提交
            // result 是 promise 链返回到事务回调的结果

            // // 日志
            utils.create_a_log(req, '学生列表', '修改状态')
            return
        }).catch(function (err) {
            res.json({
                code: 1017,
                message: '修改状态失败',
                err: 'err' + err
            })
            // 事务已被回滚
            // err 是拒绝 promise 链返回到事务回调的错误
        })
    }
    catch(error) {
        $.sendMessage(res, 1015, 'error' + error)
        return
    }
}
    
module.exports = set_student_status